package com.douguo.recipe.sina;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.douguo.recipe.OAuthWebActivity;
import com.douguo.recipe.sina.WeiboHttpClient.WeiboResponseCallBack;

/**
 * 微博操作接口
 * 
 * @author zuozp
 * 
 */
public class Weibo {
	/**
	 * OAUTH认证后的令牌 只认证一次
	 */
	public static AccessToken accessToken;

	private static final Handler handle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT)
						.show();
			}
		}

	};

	private static final WeiboResponseCallBack updateStatusCallBack = new WeiboResponseCallBack() {

		@Override
		public void onResponse(Response response) {
			handle.sendMessage(Message.obtain(handle, 1, "您的内容已经成功分享到新浪微博"));
		}

		@Override
		public void onException(int statusCode) {
			switch (statusCode) {
			case 400:
				handle.sendMessage(Message
						.obtain(handle, 1, "已经分享过这道菜了，请勿重复分享"));
				break;
			default:
				handle.sendMessage(Message.obtain(handle, 1, "发送失败，请您稍后再试"));
				break;
			}
		}
	};

	/**
	 * 发布一条信息
	 * 
	 * @param carActivity
	 * @param msg
	 */
	private static Context context;

	public static void updateStatus(final Activity carActivity,
			final String msg, final Bitmap bitmap) {
		context = carActivity;

		if (accessToken == null || accessToken.getTokenSecret() == null
				|| accessToken.getToken() == null) {
			try {
				String reuslt = SharePersistent.getInstance().getPerference(
						context, "sina_weibo_token");
				
				if (reuslt != null && reuslt.length() > 0) {
					byte[] data = Base64.decode(reuslt.getBytes("utf-8"));
					ObjectInputStream ois = new ObjectInputStream(
							new ByteArrayInputStream(data));

					accessToken = (AccessToken) ois.readObject();
					Log.w("SaveWibo", accessToken.toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (accessToken == null || accessToken.getTokenSecret() == null
				|| accessToken.getToken() == null) {

			Cache.put(WeiboHelper.WEIBO_CAR_ACTIVITY_KEY, carActivity);
			Cache.put(WeiboHelper.WEIBO_OAUTH_CALLBACK_KEY,
					new WeiboResponseCallBack() {

						@Override
						public void onResponse(Response response) {
							try {

								accessToken = new AccessToken(response);
								
								if (accessToken.getTokenSecret() == null
										|| accessToken.getToken() == null) {
									throw new Exception("Get AccessToken Error");
								}
								
								ByteArrayOutputStream baos = new ByteArrayOutputStream();
								ObjectOutputStream dos = new ObjectOutputStream(
										baos);
								dos.writeObject(accessToken);

								byte[] data = baos.toByteArray();
								String result = new String(Base64.encode(data),
										"utf-8");


								SharePersistent.getInstance().savePerference(
										context, "sina_weibo_token", result);

								if (bitmap == null) {
									WeiboHelper.updateStatus(carActivity,
											accessToken, msg,
											updateStatusCallBack);
								} else {
									new Thread() {
										public void run() {
											WeiboHelper.uploadStatus(
													carActivity, accessToken,
													bitmap, msg,
													updateStatusCallBack);
										}
									}.start();
								}
							} catch (Exception e) {
								e.printStackTrace();
								handle.sendMessage(Message.obtain(handle, 1,
								"发送失败，请您稍后再试"));
							}
						}

						@Override
						public void onException(int statusCode) {
							handle.sendMessage(Message.obtain(handle, 1,
									"发送失败，请您稍后再试"));
						}
					});

			oauth(carActivity);
		} else {
			if (bitmap == null) {
				WeiboHelper.updateStatus(carActivity, accessToken, msg,
						updateStatusCallBack);
			} else {
				new Thread() {
					public void run() {
						WeiboHelper.uploadStatus(carActivity, accessToken,
								bitmap, msg, updateStatusCallBack);
					}
				}.start();
			}
		}
	}

	/**
	 * 进行oauth认证
	 * 
	 * @param carActivity
	 */
	private static void oauth(final Activity carActivity) {
		WeiboHelper.reqRequestToken(carActivity, new WeiboResponseCallBack() {

			@Override
			public void onResponse(Response response) {
				try {
					RequestToken requestToken = new RequestToken(response);
					Cache.put("requestToken", requestToken);  
					String authenticationUrl = requestToken
							.getAuthenticationURL();

					Intent i = new Intent(carActivity, OAuthWebActivity.class);
					i.putExtra("url", authenticationUrl);
					carActivity.startActivity(i);
					

//					Uri uri = Uri.parse(authenticationUrl);
//					Intent intent = new Intent(Intent.ACTION_VIEW);
//					intent.setData(uri);
//					intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					carActivity.startActivity(intent);
				} catch (WeiboException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onException(int statusCode) {
				handle.sendMessage(Message.obtain(handle, 1, "发送失败，请您稍后再试"));
			}
		});
	}

}
